package cn.tedu._06vehicle.controller;

import cn.tedu._06vehicle.base.response.JsonResult;
import cn.tedu._06vehicle.base.response.StatusCode;
import cn.tedu._06vehicle.mapper.UserMapper;
import cn.tedu._06vehicle.pojo.dto.UserLoginParam;
import cn.tedu._06vehicle.pojo.dto.UserRegParam;
import cn.tedu._06vehicle.pojo.entity.User;
import cn.tedu._06vehicle.pojo.vo.UserLoginVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/v1/user/")
@Tag(name="01-用户管理")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult addUser(@RequestBody @Validated UserRegParam param){
        log.debug("param:"+param);
        //获取用户输入的用户名
        String username=param.getUsername();
        //验证用户输入的用户名是否已存在
        int rows=userMapper.selectUserByUsername(username);
        if (rows>0){//用户已存在
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user=new User();
        BeanUtils.copyProperties(param,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("user："+user);
        userMapper.insertUser(user);
        return JsonResult.OK();

    }
    @PostMapping("login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult loginUser(@RequestBody UserLoginParam param,HttpSession session
    ){
        log.debug("登录参数:"+param);

        UserLoginVO loginVO=userMapper.selectUserByUsernameAndPassword(param);

        if (loginVO !=null){
            //把用户的标识存入session会话中
            session.setAttribute("user",loginVO);
            return JsonResult.OK(loginVO);
        }else {
            return new JsonResult(StatusCode. USERNAME_PASSWORD_ERROR);
        }

    }

    @GetMapping("current")
    @Operation(summary = "查询当前登录用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        //服务器中获取会话标识
        //loginVo :null | {"id":101,"username":"擎天柱"
        UserLoginVO loginVo=(UserLoginVO) session.getAttribute("user");

        return JsonResult.OK(loginVo);
    }


    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public JsonResult logoutUser(HttpSession session){
        //退出登录,删除session会话的用户标识
        session.removeAttribute("user");
        return JsonResult.OK();
    }





}
